package tenumn.energytech.registrys.machine;

import io.github.uicdb.liba.api.blocks.data.BlockFacingFor4Side;
import io.github.uicdb.liba.api.util.LazyUtil;
import net.minecraft.core.BlockPos;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.EntityBlock;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityTicker;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandlerModifiable;
import org.jetbrains.annotations.Nullable;

import javax.annotation.Nonnull;
import javax.annotation.ParametersAreNonnullByDefault;

@ParametersAreNonnullByDefault
public abstract class MachineBlock extends BlockFacingFor4Side implements EntityBlock {
    public MachineBlock(Properties properties) {
        super(properties);
    }

    @Nullable
    @Override
    public <T extends BlockEntity> BlockEntityTicker<T> getTicker(Level pLevel, BlockState pState, BlockEntityType<T> pBlockEntityType) {
        return LazyUtil.getTicker();
    }

    protected boolean shouldDropInventory(Level level, BlockPos pos, BlockState state) {
        return true;
    }

    @Override
    @SuppressWarnings("deprecation")
    public void onRemove(@Nonnull BlockState state, @Nonnull Level level, @Nonnull BlockPos pos, @Nonnull BlockState newState, boolean isMoving) {
        if (!level.isClientSide && (!state.is(newState.getBlock()) || !newState.hasBlockEntity()) && this.shouldDropInventory(level, pos, state)) {
            BlockEntity be = level.getBlockEntity(pos);
            if (be != null) {
                be.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null).ifPresent(handler -> {
                    if (handler instanceof IItemHandlerModifiable modifiable) {
                        for (int i = 0; i < modifiable.getSlots(); i++) {
                            ItemStack stack = modifiable.getStackInSlot(i);
                            ItemEntity entity = new ItemEntity(level, pos.getX() + 0.5, pos.getY() + 0.1, pos.getZ() + 0.5, stack.copy());
                            level.addFreshEntity(entity);
                            modifiable.setStackInSlot(i, ItemStack.EMPTY);
                        }
                    }
                });
            }
        }
        super.onRemove(state, level, pos, newState, isMoving);
    }
}
